
do "E:/ReplicateBuild/02_code/00_environment/00_set_environment.do"

use "$basedata/estimationdata/All_T_J/teach_pref_est_data.dta", clear

set seed 38239



** estimate rate applicant applies to earlier vs later posting from same school



keep if choiceset==1


bys itidx ncerdc_schlcode app_year: egen numvacanciesinchoiceset = sum(choiceset)

keep if numvacanciesinchoiceset==2

bys itidx ncerdc_schlcode app_year: egen mindate = min(PostingDate)
bys itidx ncerdc_schlcode app_year: egen maxdate = max(PostingDate)

gen pos1 = PostingDate==mindate & PostingDate!=maxdate
gen pos2 = PostingDate!=mindate & PostingDate==maxdate


gen applied1 = applied if pos1==1
gen applied2 = applied if pos2==1

keep if pos1==1 | pos2==1

bys itidx app_year: egen Nchoice = count(applied)
bys itidx app_year: egen Napp = sum(applied)

replace Napp = Napp-applied
replace Nchoice = Nchoice-1

gen applied_others_1 = Napp/Nchoice if applied==1 & pos1==1
gen applied_others_2 = Napp/Nchoice if applied==1 & pos2==1


collapse (max) applied1 applied2 (mean) applied_others_*, by(itidx ncerdc_schlcode app_year)

drop if applied1==. | applied2==.

tab applied1 applied2

bys applied1: summ applied2
bys applied2: summ applied1

gen applied_2_given_1 = applied2 if applied1==1
gen applied_1_given_2 = applied1 if applied2==1


summ applied_2_given_1
local applied_forward = r(mean)
local Nfor = r(N)
summ applied_1_given_2
local applied_backward = r(mean)
local Nback = r(N)

summ applied1
local mean1unc = r(mean)
summ applied2
local mean2unc = r(mean)

summ applied_others_1
local mean1oth = r(mean)
summ applied_others_2
local mean2oth = r(mean)


mat a = (`Nfor',`applied_forward',`mean2unc')
mat b = (`Nback',`applied_backward',`mean1unc')

gen avar = .
gen bvar = .

label var avar "Applied to Second Vacancy, Given Applied to First"
label var bvar "Applied to First Vacancy, Given Applied to Second"


mat rownames a = avar
mat rownames b = bvar

mat c = a\b


frmttable using "$tables/multivacancy_app_rates", statmat(c) replace va tex fra ///
	ctitles("","N","Mean","Unconditional") ///
	sdec(0,2,2 \ 0,2,2) 

	